<template>
  <div class="app-container">
    <el-form class="filter-container" :inline="true">
      <el-form-item style="margin-bottom: 0!important;">
        <el-input
          @keyup.enter.native="getList" style="width: 250px;" class="filter-item"
          placeholder="请输入板块/股票" v-model="listQuery.phoneticChars"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="创建人" style="margin-bottom: 0!important;">
        <el-input
          @keyup.enter.native="getList" style="width: 150px;" class="filter-item"
          placeholder="请输入创建人" v-model="listQuery.creater"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="创建时间" style="margin-bottom: 0!important;">
        <el-date-picker type="datetimerange" :default-time="['00:00:00', '23:59:59']"
          @keyup.enter.native="getList" style="width: 450px;" class="filter-item"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" v-model="time" :picker-options="pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-button
        class="filter-item" type="primary" v-waves icon="el-icon-search" @click="getList"
      >
        {{$t('table.search')}}
      </el-button>
      <el-button
        class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="success"
        icon="el-icon-plus"
      >新增
      </el-button>
    </el-form>

    <el-table stripe
      :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="加载中..." border fit
      highlight-current-row
      style="width: 100%"
    >
      <!--<el-table-column align="center" type="selection" width="55">-->
      <!--</el-table-column>-->
      <el-table-column align="center" label="板块代码">
        <template slot-scope="scope">
          <span>{{scope.row.code}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="名称">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建人">
        <template slot-scope="scope">
          <span>{{scope.row.creater}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createTime}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="'板块股票'" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            style="width: auto" type="success" size="mini" @click="handleStockUpdate(scope.row)"
          >编辑板块股票
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('table.actions')" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)"
              class="button-icon el-icon-edit"></el-button>
          </el-tooltip>
          <el-tooltip v-if="scope.row.status!='deleted'" content="删除" placement="top">
            <el-button
              size="mini" type="danger" class="button-icon el-icon-delete"
              @click="handleDelete(scope.row)"
            >
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="listQuery.pageNum"
        :page-sizes="[10,20,30, 50]" :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="130px"
        style='margin: 24px;'
      >
        <el-form-item label="板块名称" prop="name">
          <el-input v-model="temp.name" type="text" placeholder="请输入">
          </el-input>
          <el-input class="hide">
          </el-input>
        </el-form-item>
        <!--<el-form-item label="板块代码" prop="code">-->
        <!--<el-input v-model="temp.code" type="text" placeholder="请输入">-->
        <!--</el-input>-->
        <!--</el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
        <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogStockVisible" style="text-align: center">
      <el-form :model="temp" label-position="left" label-width="130px">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="查询股票">
              <el-input v-model="stockSearch" placeholder="请输入" @keyup.enter.native="searchStock()">
                <el-button
                  type="button"
                  slot="append" icon="el-icon-search" @keyup.enter.native="searchStock()"
                  @click='searchStock()'
                ></el-button>
              </el-input>
              <input type="text" disabled hidden>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-transfer
        style="text-align: left; display: inline-block"
        v-model="tempStock"
        :titles="['股票列表', '已选择']"
        :button-texts="['移除', '添加']"
        :format="{noChecked: '${total}',hasChecked: '${checked}/${total}'}"
        :data="stockLib"
      >
      </el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogStockVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="updateStockData">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { plateList, plateAdd, plateUpdate, plateDelete, stockList, stockListUpdate } from '../../api/group'
  import { articleStockList } from '../../api/article'
  import waves from '@/directive/waves' // 水波纹指令

  export default {
    name: 'complexTable',
    directives: {
      waves
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: null,
        listLoading: false,
        listQuery: {
          type: 2,
          pageNum: 1,
          pageSize: 20,
          phoneticChars: '',
          creater: '',
          startTime: '',
          endTime: '',
          code: ''
        },
        time: ['', ''],
        showReviewer: false,
        temp: {
          code: '',
          name: '',
          author: '',
          createTime: ''
        },
        stockLib: [],
        tempStock: [],
        tempStockId: '',
        oldStockList: [],
        stockSearch: '',
        dialogFormVisible: false,
        dialogStockVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        pvData: [],
        rules: {
          code: [{ type: 'string', required: true, message: '请输入...', trigger: 'change' }],
          name: [{ type: 'string', required: true, message: '请输入...', trigger: 'change' }],
          author: [{ type: 'string', required: true, message: '请输入...', trigger: 'change' }],
          createTime: [{ type: 'string', message: '请输入...', trigger: 'change' }]
        },
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() - 1000
              const start = end + 1000 - 3600 * 1000 * 24
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三天',
            onClick(picker) {
              const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() - 1000
              const start = end + 1000 - 3600 * 1000 * 24 * 3
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() - 1000
              const start = end + 1000 - 3600 * 1000 * 24 * 7
              picker.$emit('pick', [start, end])
            }
          }]
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      // handleSearch() {
      //   this.getList()
      // },
      searchStock() {
        const params = {
          pageNum: 1,
          pageSize: 9999,
          phoneticChars: this.stockSearch
        }
        articleStockList(params).then(response => {
          let stocks = []
          this.stockLib = response.Data.map(e => {
            stocks.push(`${e.name}(${e.code})`)
            return {
              key: `${e.name}(${e.code})`,
              label: `${e.name}(${e.code})`
            }
          })
          this.tempStock.forEach(e => {
            if (stocks.indexOf(e) === -1) {
              this.stockLib.push({
                key: e,
                label: e
              })
            }
          })
        })
      },
      getList() {
        this.listLoading = true
        if (this.time) {
          this.listQuery.startTime = this.time[0]
          this.listQuery.endTime = this.time[1]
        } else {
          this.listQuery.startTime = ''
          this.listQuery.endTime = ''
        }
        plateList(this.listQuery).then(response => {
          // console.log(response)
          this.listLoading = false
          this.list = response.Data
          this.total = parseInt(response.total)
        })
      },
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      resetTemp() {
        this.temp = {
          code: '',
          name: '',
          author: '',
          createTime: ''
        }
        this.tempStock = []
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            plateAdd(this.temp).then(() => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            plateUpdate(tempData).then(() => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleStockUpdate(row) {
        this.stockSearch = ''
        this.dialogStockVisible = true
        this.tempStockId = row.code
        const params = {
          pageNum: 1,
          pageSize: 9999,
          queryKey: row.code
        }
        stockList(params).then(response => {
          this.oldStockList = response.Data.map(e => e.code)
          this.tempStock = response.Data.map(e => `${e.name}(${e.code})`)
          this.stockLib = response.Data.map(e => ({
            key: `${e.name}(${e.code})`,
            label: `${e.name}(${e.code})`
          }))
          this.dialogStatus = 'update'
          this.dialogStockVisible = true
        })
      },
      updateStockData() {
        const tempData = {}
        // const codeReg = new RegExp('(?<=\\().*(?=\\))')
        const newStockList = this.tempStock.map(e => e.split('(')[1].split(')')[0])
        tempData.plateCode = this.tempStockId
        tempData.stockAddList = newStockList.filter(e => this.oldStockList.indexOf(e) === -1)
        tempData.stockDelList = this.oldStockList.filter(e => newStockList.indexOf(e) === -1)
        tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
        stockListUpdate(tempData).then(() => {
          this.getList()
          this.dialogStockVisible = false
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      handleDelete(row) {
        this.$confirm('确认删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          plateDelete(row).then(() => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    }
  }
</script>

<style>
  .hide {
    display: none;
  }

</style>
